<template>
  <!--使用自定义指令实现元素拖动-->
  <div v-move class="box">
    <div class="header">
      标题
    </div>
    <div class="content">
      内容
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, Directive, DirectiveBinding } from 'vue'

const vMove: Directive = (el: HTMLElement, binding: DirectiveBinding) => {
  let moveElement: HTMLDivElement = el.firstElementChild as HTMLDivElement

  const mousedown = (e: MouseEvent) => {
    let X = e.clientX - el.offsetLeft
    let Y = e.clientY - el.offsetTop
    const move = (e: MouseEvent) => {
      el.style.left = e.clientX - X + 'px'
      el.style.top = e.clientY - Y + 'px'
      el.style.cursor = 'move'
    }

    const removeEvent = () => {
      el.style.cursor = ''
      document.removeEventListener('mousemove', move)
      document.removeEventListener('mouseup', removeEvent)
    }

    document.addEventListener('mousemove', move)
    document.addEventListener('mouseup', removeEvent)
    
  }

  // 给元素绑定鼠标按下事件
  moveElement.addEventListener('mousedown', mousedown)
}

</script>

<style lang='scss' scoped>
.box {
  position: fixed;
  width: 400px;
  height: 400px;
  border: 1px solid #000;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);


  .header {
    height: 30px;
    background-color: black;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>